package org.core;

import org.constant.Constant;
import org.util.HttpUtils;
import org.util.LogUtils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

/**
 * @Auther: qingle
 * @Date: 2024/9/9-1:31
 * @Description: 分块下载任务
 * @version: 1.0
 */
public class DownloaderTask implements Callable<Boolean> {

	// 下载链接
	private String url;

	// 开始位置
	private long startPos;

	// 结束位置
	private long endPos;

	// 表示当前是哪一部分
	private long part;

	private CountDownLatch countDownLatch;

	public DownloaderTask(String url, long startPos, long endPos, long part, CountDownLatch countDownLatch) {
		this.url = url;
		this.startPos = startPos;
		this.endPos = endPos;
		this.part = part;
		this.countDownLatch = countDownLatch;
	}

	@Override
	public Boolean call() throws Exception {

		// 获取文件名
		String httpFileName = HttpUtils.getHttpFileName(url);

		// 分块的文件名
		String partFileName = httpFileName + "_" + part;

		// 下载文件路径
		String fileName = Constant.PATH + partFileName;

		// 获取分块下载的链接
		HttpURLConnection httpURLConnection = HttpUtils.getHttpURLConnection(url, startPos, endPos);

		System.out.println("开始下载：" + partFileName);

		try(
			InputStream inputStream  = httpURLConnection.getInputStream();
			// 包装输入流为带缓冲区的输入流，以提高读取效率
			BufferedInputStream bis = new BufferedInputStream(inputStream);

			// 创建文件输出流，用于将数据写入到目标文件中
			RandomAccessFile accessFile = new RandomAccessFile(httpFileName, "rw");

			) {

			byte[] buffer = new byte[Constant.BYTE_SIZE];
			int len = -1;
			// 循环读取数据
			while ((len = bis.read(buffer)) != -1) {
				// 1s内下载数据之和，通过原子类进行操作
				DownloadInfoThread.downSize.add(len);
				// 写入文件
				accessFile.write(buffer, 0, len);
			}

			return false;
		} catch (FileNotFoundException e) {
			LogUtils.error("文件不存在");
			return false;
		} catch (Exception e) {
			LogUtils.error("文件下载出现异常，联系管理员");
			return false;
		} finally {
			httpURLConnection.disconnect();

			countDownLatch.countDown();
		}

//		return true;
	}
}
